<!-- File: FilterById.vue -->
<template>
  <div>
    <h2>结果：</h2>
    <ul>
      <li v-for="item in filteredData" :key="item.name">
        {{ item.name }} (ID: {{ item.id }})
      </li>
    </ul>
  </div>
</template>

<script lang="ts" setup>
interface Item {
  id: number
  name: string
}
const data: Item[] = [
  { id: 1, name: 'A' },
  { id: 2, name: 'B' },
  { id: 1, name: 'C' },
  { id: 3, name: 'D' },
]

// 方法一：使用 filter
const result = data.filter((item) => item.id === 1)
console.log(result)
// 方法二：使用 reduce
const filteredData = data.reduce<Item[]>((acc, item) => {
  if (item.id === 1) acc.push(item)
  return acc
}, [])
console.log(filteredData)
// 方法三：使用 for 循环
const result_3 = []
for (let i = 0; i < data.length; i++) {
  if (data[i].id === 1) {
    result_3.push(data[i])
  }
}
console.log(result_3)
</script>

<style scoped>
h2 {
  font-weight: bold;
  margin-bottom: 8px;
}
</style>
